<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//用户登陆
class Welcome extends ST_Controller {

	public function __construct() {
        parent::__construct();
        // 判断用户是否手机登录
        $this->load->library('mobile_lib');
        $is = $this->mobile_lib->is_mobile_request();
        $this->session->set_userdata('mobile', $is);

        //判断session是否存在
        if(!empty($_SESSION['user'])){
            redirect(site_url('home'));
        }
    }


	public function index()
	{
		$cap = $this->verify();
        if(!$_SESSION['mobile']){
            $this->load->view('login',array('cap'=>$cap));
        }else{
            $this->load->view('mobile/login',array('cap'=>$cap));
        }

	}

	/**
	 * 用户登录
	 */
	public function login(){
		if(!$this->input->is_ajax_request()){
			show_404();
		}

		$post = $this->input->post(NULL);

		if($post['cap'] != $this->session->word){
			die('验证码错误！');
		}

		unset($_SESSION['word']);

		if(empty($post['username']) || empty($post['password'])){
			die('帐号或者密码不能为空');
		}

		$this->load->model('users_mdl');

		$this->db->where('username',$post['username']);
		$this->db->where('password',md5($post['password']));
		$this->db->select('id,username,status,login_time,group_id');
		$res = $this->users_mdl->get_one();

		if(empty($res['id'])){
			die('帐号或者密码错误！');
		}

        if($res['status'] != 3 && $_SESSION['mobile']){
            die('管理员不能登录wap版本');
        }

		if($res['status'] == 4){
			die('您的帐号已经过期，请联系网站管理员！');
		}

        //更新登录时间
        $this->db->where('id',$res['id']);
        $this->users_mdl->update(array('login_time'=>time()));

        //查询帐号
        $group_name = '';
        if($res['status'] == 1){
            $group_name = '超级管理员';
        }
        if($res['status'] == 2){
            $group_name = '管理员';
        }
        if($res['status'] == 3){
            $this->load->model('group_mdl');
            $this->db->where('id',$res['group_id']);
            $this->db->select('title');
            $group_name = $this->group_mdl->get_one();
            $group_name = $group_name['title'];
        }

        //记录登录日志
        $this->load->model('session_mdl');
        $data = array(
            'login_time' => time(),
            'user_id' => $res['id']
        );
        $this->session_mdl->create($data);

        $this->db->where('login_time <',60*60*12*30*3);
        $this->session_mdl->delete();

        $this->session->set_userdata('group_name',$group_name);
		$this->session->set_userdata('group',$res['status']);
		$this->session->set_userdata('user',$res);

		echo 1;
	}

	/**
     * 验证码刷新
     */
    public function reset_cap(){
        $cap = $this->verify();
        echo $cap['image'];
    }

	/**
	 * 验证码
	 */
	public function verify(){
		$this->load->helper('captcha');
        $vals = array(
            'word'      => '',
            'img_path'  => './captcha/',
            'img_url'   => base_url('/captcha/'),
            'font_path' => './public/fonts/droidsansmono__.ttf',
            'img_width' => '277',
            'img_height'    => 60,
            'expiration'    => 1,
            'word_length'   => 6,
            'font_size' => 25,
            'img_id'    => 'Imageid',
            'pool'      => '0123456789',

            // White background and border, black text and red grid
            'colors'    => array(
                'background' => array(255, 255, 255),
                'border' => array(215, 255, 255),
                'text' => array(0, 0, 0),
                'grid' => array(255, 40, 40)
            )
        );
        $cap = create_captcha($vals);
        //转换为一次性数据
        $this->session->set_userdata('word', $cap['word']);
        return $cap;
	}

    /**
     * 用户注册
     */
    public function registered(){
        if($this->input->is_ajax_request()){
            $post = $this->input->post();
            /** 验证 */
            if(intval($post['pid']) < 1){
                die('系统错误');
            }

            //Model
            $this->load->model('users_mdl');
            $this->load->model('uinfo_mdl');
            $this->load->model('group_mdl');
            $this->load->model('mess_mdl');

            if(!preg_match("/\w{6,20}/",$post['user_name'])){
                die('登录帐号格式不正确， 请输入字母、数字、下划线，6-20个字符');
            }

            $this->db->where('username',$post['user_name']);
            $res_is = $this->users_mdl->get_count();
            if(!empty($res_is)){
                die('该登录帐号已经存在，请修改');
            }

            if($post['pass'] != $post['password_1']){
                die('两次密码输入不一致');
            }
            if(!preg_match("/\w{6,20}/",$post['pass'])){
                die('密码格式不正确， 请输入字母、数字、下划线，6-20个字符');
            }

            if(empty($post['name'])){
                die('真实姓名不能为空');
            }

            if(!preg_match("/1[0-9]{10}/",$post['phone'])){
                die('联系电话格式错误，请填写11位的手机号码');
            }

            if(!preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$post['email'])){
                die('联系邮箱格式错误，请填写正确的邮箱地址，如 zbzmall@163.com');
            }

            if(!preg_match("/^[0-9]{6,14}$/",$post['qq']) && !empty($post['qq'])){
                die('请正确填写QQ');
            }

            if(!preg_match("/^.{5，30}$/",$post['weixin']) && !empty($post['weixin'])){
                die('请正确填写微信帐号');
            }

            /** 获取额度最低的权限 */
            $this->db->select_min('condition');
            $min_condition = $this->group_mdl->get_one();

            $this->db->where('condition',$min_condition['condition']);
            $res_group = $this->group_mdl->get_one();

            /** 查询上级用户层级 */
            $this->db->where('id',intval($post['pid']));
            $this->db->select('tier');
            $tier = $this->users_mdl->get_one();

            //加入用户表
            $data = array(
                'username' => $post['user_name'],
                'password' => md5($post['pass']),
                'login_time' => time(),
                'status' => 3,
                'create_time' => time(),
                'group_id' => $res_group['id'],
                'pid' => intval($post['pid']),
                'tier' => $tier['tier']+1
            );

            $this->db->trans_start();
            $users_id = $this->users_mdl->create($data);

            //创建用户详情表
            $data = array(
                'id' => $users_id,
                'name' => $post['name'],
                'phone' => $post['phone'],
                'email' => $post['email'],
                'qq' => $post['qq'],
                'weixin' => $post['weixin'],
                'address' => $post['address'],
                'company' => $post['company'],
                'money' => 0.0
            );
            $res = $this->uinfo_mdl->create($data);

            //修改上线所有下线用户数量（所有上级在本身的基础上加1）
            $this->users_mdl->set_num($post['pid']);

            /**
             * 系统通知
             */
            $data = array(
                'sending' => 1,
                'receive' => $post['pid'],
                'content' => sprintf('用户： %s，通过您注册了本系统，成为您的下线，感谢您的支持',$post['user_name']),
                'create_time' => $_SERVER['REQUEST_TIME'],
                'pid' => 0
            );
            $this->mess_mdl->create($data);

            $data = array(
                'sending' => 1,
                'receive' => $users_id,
                'content' => sprintf('尊敬的%s，您好欢迎您的注册，感谢您对本系统的支持',$post['user_name']),
                'create_time' => $_SERVER['REQUEST_TIME'],
                'pid' => 0
            );
            $this->mess_mdl->create($data);

            $this->db->trans_complete();

            echo $res ? 1:'注册用户失败！';

        }else{
            $puid = $this->input->get('puid');

            if(intval($puid) < 1){
                redirect(site_url('home'));
            }

            $data = array(
                'pid' => $puid
            );
            if($_SESSION['mobile']){
                $this->load->view('mobile/registered',$data);
            }else{
                $this->load->view('registered',$data);
            }
        }

    }



}
